package org.example.pool;

import java.util.Random;
import java.util.concurrent.Semaphore;

public class TestCar {
    private static Semaphore semaphore = new Semaphore(3);
    public static void main(String[] args) {
        for(int i=1;i<=5;i++){
            Thread t = new Thread(()->{
                System.out.println(Thread.currentThread().getName()+"来到了停车场");
                if(semaphore.availablePermits()==0){
                    System.out.println("车位已满，请"+Thread.currentThread().getName()+"排队！");
                }
                try {
                    //尝试获取令牌
                    semaphore.acquire();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName()+"进入停车场！");
                try {
                    Thread.sleep(new Random().nextInt(10000));
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                System.out.println(Thread.currentThread().getName()+"离开停车场！");
                semaphore.release();
            });
            t.start();
        }
    }
}
